package com.promise.jokerdream.response.parser

import com.promise.jokerdream.response.phone.BrotherData
import com.promise.jokerdream.response.phone.QingLvData
import com.promise.jokerdream.response.phone.ShiFuData
import com.promise.jokerdream.response.phone.TuDiData
import com.promise.jokerdream.response.phone.BossData
import com.promise.jokerdream.response.phone.XiaLvXmlResponse
import org.jsoup.Jsoup

/**
 * 侠侣XML解析器
 * 专门用于解析大乐斗侠侣相关的XML数据
 * 基于Jsoup实现
 */
class XiaLvXmlParser : BaseXmlParser<XiaLvXmlResponse>() {
    
    /**
     * 解析侠侣XML数据
     * @param xmlString XML字符串
     * @return 解析结果
     */
    fun parseXiaLvXml(xmlString: String): XmlParseResult<XiaLvXmlResponse> {
        return parseXml(xmlString)
    }
    
    /**
     * 实现基类的具体解析逻辑
     * @param xmlString XML字符串
     * @return 解析后的侠侣数据
     */
    override fun doParse(xmlString: String): XiaLvXmlResponse {
        val extractedData = mutableMapOf<String, Any>()
        
        try {
            val doc = Jsoup.parse(xmlString)
            val divElement = doc.selectFirst("div#id")
            
            if (divElement != null) {
                val html = divElement.html()
                parseDivContent(html, extractedData)
            }
        } catch (e: Exception) {
            // 解析失败，返回空数据
        }
        
        return XiaLvXmlResponse(
            actionResult = extractedData["actionResult"] as? String ?: "",
            currentVitality = extractedData["vitality"] as? String ?: "0/100",
            bossList = extractedData["bossList"] as? List<BossData> ?: emptyList(),
            marry = extractedData["qingList"] as? QingLvData,
            shiFu = extractedData["shiList"] as? ShiFuData,
            tuDiList = extractedData["tuList"] as? List<TuDiData> ?: emptyList(),
            brotherList = extractedData["baiList"] as? List<BrotherData> ?: emptyList()
        )
    }
    
    /**
     * 解析div内容
     */
    private fun parseDivContent(html: String, data: MutableMap<String, Any>) {
        // 统一替换<br />为<br/>，确保Jsoup能正确识别
        val normalizedHtml = html.replace(Regex("<br\\s*/?>"), "<br/>")
        val doc = Jsoup.parse(normalizedHtml)
        val divElement = doc.selectFirst("div#id")
        
        // 提取体力值
        val vitalityRegex = Regex("当前体力值：([^\\s]+)")
        val vitalityMatch = vitalityRegex.find(html)
        if (vitalityMatch != null) {
            data["vitality"] = vitalityMatch.groupValues[1]
        }

        // 按行分割内容
        val lines = normalizedHtml.split("<br/>")
        // 解析其他数据
        for (line in lines) {
            val trimmedLine = line.trim()
            if (trimmedLine.isEmpty()) continue
            
            when {
                trimmedLine.contains("侠：") -> {
                    val bossData = parseBossData(trimmedLine)
                    if (bossData != null) {
                        val bossList = data.getOrPut("bossList") { mutableListOf<BossData>() } as MutableList<BossData>
                        bossList.add(bossData)
                    }
                }
                trimmedLine.contains("情：") -> {
                    val qingData = parseQingData(trimmedLine)
                    if (qingData != null) {
                        data["qingList"] = qingData
                    }
                }
                trimmedLine.contains("师：") -> {
                    val shiData = parseShiData(trimmedLine)
                    if (shiData != null) {
                        data["shiList"] = shiData
                    }
                }
                trimmedLine.contains("徒：") -> {
                    val tuDiData = parseTuData(trimmedLine)
                    if (tuDiData != null) {
                        val tuDiList = data.getOrPut("tuList") { mutableListOf<TuDiData>() } as MutableList<TuDiData>
                        tuDiList.add(tuDiData)
                    }
                }
                trimmedLine.contains("拜：") -> {
                    val brotherData = parseBaiData(trimmedLine)
                    if (brotherData != null) {
                        val brotherList = data.getOrPut("baiList") { mutableListOf<BrotherData>() } as MutableList<BrotherData>
                        brotherList.add(brotherData)
                    }
                }
            }
        }
    }
    
    /**
     * 解析侠数据
     */
    private fun parseBossData(lineText: String): BossData? {
        return try {
            val nameRegex = Regex("侠：.*?<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("</a>\\s*(\\d+)(?:级)?\\s*")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val isFoughtRegex = Regex("已乐斗")
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            val isFought = isFoughtRegex.containsMatchIn(lineText)
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                BossData(
                    name = nameMatch.groupValues[1].trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析情数据
     */
    private fun parseQingData(lineText: String): QingLvData? {
        return try {
            val nameRegex = Regex("情：.*?<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("</a>\\s*(\\d+)级\\s*")
            val factionRegex = Regex("级\\s*([^\\s<]+)")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val isFought = "已乐斗" in lineText
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val factionMatch = factionRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                QingLvData(
                    name = nameMatch.groupValues[1].replace("&nbsp;", "").trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    faction = factionMatch?.groupValues?.get(1) ?: "",
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析师数据
     */
    private fun parseShiData(lineText: String): ShiFuData? {
        return try {
            val nameRegex = Regex("师：.*?<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("</a>\\s*(\\d+)级\\s*")
            val factionRegex = Regex("级\\s*([^\\s<]+)")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val isFought = "已乐斗" in lineText
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val factionMatch = factionRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                ShiFuData(
                    name = nameMatch.groupValues[1].trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    faction = factionMatch?.groupValues?.get(1) ?: "",
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析徒数据
     */
    private fun parseTuData(lineText: String): TuDiData? {
        return try {
            val nameRegex = Regex("徒：.*?<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("</a>\\s*(\\d+)级\\s*")
            val factionRegex = Regex("级\\s*([^\\s<]+)")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val specialSkillRegex = Regex("神拳")
            val isFought = "已乐斗" in lineText
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val factionMatch = factionRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            val specialSkillMatch = specialSkillRegex.find(lineText)
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                TuDiData(
                    name = nameMatch.groupValues[1].trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    faction = factionMatch?.groupValues?.get(1) ?: "",
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought,
                    specialSkill = if (specialSkillMatch != null) "神拳" else null
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
    
    /**
     * 解析拜数据
     */
    private fun parseBaiData(lineText: String): BrotherData? {
        return try {
            val nameRegex = Regex("拜：.*?<a[^>]*>([^<]+)</a>")
            val levelRegex = Regex("</a>\\s*(\\d+)级\\s*")
            val factionRegex = Regex("级\\s*([^\\s<]+)")
            val uidRegex = Regex("B_UID=(\\d+)")
            val fightUrlRegex = Regex("<a[^>]*href=\"([^\"]*fight[^\"]*)\"[^>]*>")
            val specialSkillRegex = Regex("神拳")
            val isFought = "已乐斗" in lineText
            
            val nameMatch = nameRegex.find(lineText)
            val levelMatch = levelRegex.find(lineText)
            val factionMatch = factionRegex.find(lineText)
            val uidMatch = uidRegex.find(lineText)
            val fightUrlMatch = fightUrlRegex.find(lineText)
            val specialSkillMatch = specialSkillRegex.find(lineText)
            
            if (nameMatch != null && levelMatch != null && uidMatch != null && fightUrlMatch != null) {
                BrotherData(
                    name = nameMatch.groupValues[1].trim(),
                    level = levelMatch.groupValues[1].toInt(),
                    uid = uidMatch.groupValues[1],
                    faction = factionMatch?.groupValues?.get(1) ?: "",
                    fightUrl = fightUrlMatch.groupValues[1],
                    isFought = isFought,
                    specialSkill = if (specialSkillMatch != null) "神拳" else null
                )
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }
}
